package avicit.bdp.dms.prm.rest;

import avicit.bdp.common.dto.BdpPrmEngineResourceDTO;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.prm.service.BdpPrmEngineResourceService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/** 存储引擎、资源引擎管理 */
@RestController
@Api(tags = "存储引擎、资源引擎管理")
@RequestMapping("/api/bdp/dms/prm/engine/manage/")
public class BdpPrmEngineResourceRest {

  @Autowired private BdpPrmEngineResourceService bdpPrmEngineResourceService;

  @Autowired private ConvertColumnClient convertColumnClient;

  /** 按条件分页查询 */
  @ApiOperation(value = "按条件分页查询")
  @ApiImplicitParams({
    @ApiImplicitParam(value = "类型：0--计算引擎；1--存储引擎", name = "type", dataType = "int"),
    @ApiImplicitParam(
        value = "资源或引擎类型 0-Flink 1-Spark 2-hdfs 3-oss",
        name = "resourceType",
        dataType = "int"),
    @ApiImplicitParam(value = "查询关键字", name = "keyWords", dataType = "String"),
    @ApiImplicitParam(value = "密级", name = "secretLevel", dataType = "String"),
    @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "int"),
    @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "int")
  })
  @GetMapping("/searchByPage")
  public ResponseMsg<QueryRespBean<BdpPrmEngineResourceDTO>> searchByPage(
      @RequestParam Integer type,
      @RequestParam(required = false) Integer resourceType,
      @RequestParam(required = false) String keyWords,
      @RequestParam(required = false) String secretLevel,
      @RequestParam(defaultValue = "1", required = false) Integer pageNo,
      @RequestParam(defaultValue = "10", required = false) Integer pageSize) {

    ResponseMsg<QueryRespBean<BdpPrmEngineResourceDTO>> responseMsg = new ResponseMsg<>();
    QueryRespBean<BdpPrmEngineResourceDTO> result =
        bdpPrmEngineResourceService.searchBdpPrmEngineResourceByPage(
            type, resourceType, keyWords, pageNo, pageSize, secretLevel);
    try {
      valueConvert(result.getResult());
    } catch (Exception e) {
      e.printStackTrace();
    }
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /**
   * 通过主键查询单条记录
   *
   * @param id 主键id
   */
  @ApiOperation(value = "通过主键查询单条记录")
  @ApiImplicitParam(value = "主键id", name = "id", dataType = "String", required = true)
  @GetMapping("/viewDetail")
  public ResponseMsg<BdpPrmEngineResourceDTO> viewDetail(@RequestParam("id") String id) {
    ResponseMsg<BdpPrmEngineResourceDTO> responseMsg = new ResponseMsg<>();
    BdpPrmEngineResourceDTO bdpPrmEngineResource =
        bdpPrmEngineResourceService.queryBdpPrmEngineResourceByPrimaryKey(id);
    if (bdpPrmEngineResource != null) {
      try {
        valueConvert(Arrays.asList(bdpPrmEngineResource));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    responseMsg.setResponseBody(bdpPrmEngineResource);
    return responseMsg;
  }

  /**
   * 新增对象
   *
   * @param bdpPrmEngineResource 保存对象
   */
  @PostMapping("/save")
  @ApiOperation(value = "新增对象")
  public ResponseMsg<String> save(@RequestBody BdpPrmEngineResourceDTO bdpPrmEngineResource) {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        bdpPrmEngineResourceService.insertBdpPrmEngineResource(bdpPrmEngineResource));
    return responseMsg;
  }

  /**
   * 修改全部对象字段
   *
   * @param bdpPrmEngineResource 修改对象
   */
  @PostMapping("/updateAll")
  @ApiOperation(value = "修改对象")
  public ResponseMsg<Integer> updateAll(@RequestBody BdpPrmEngineResourceDTO bdpPrmEngineResource) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        bdpPrmEngineResourceService.updateBdpPrmEngineResource(bdpPrmEngineResource));
    return responseMsg;
  }

  /** 按主键单条删除 */
  @ApiOperation(value = "按主键单条删除")
  @ApiImplicitParam(value = "主键id", name = "id", dataType = "String", required = true)
  @DeleteMapping("/deleteById")
  public ResponseMsg<Integer> deleteById(@RequestParam("id") String id) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpPrmEngineResourceService.deleteBdpPrmEngineResourceById(id));
    return responseMsg;
  }

  /**
   * 批量删除
   *
   * @param ids 待删除的主键ID
   */
  @PostMapping("/batchDelete")
  @ApiImplicitParam(value = "主键id集合（用于批量操作）", name = "ids", dataType = "List", required = true)
  @ApiOperation(value = "批量删除")
  public ResponseMsg<Integer> deleteByIds(@RequestBody List<String> ids) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpPrmEngineResourceService.deleteBdpPrmEngineResourceByIds(ids));
    return responseMsg;
  }

  @ApiOperation(value = "设置默认")
  @ApiImplicitParam(value = "主键id", name = "id", dataType = "String")
  @GetMapping("/defaultResource")
  public ResponseMsg<Integer> defaultResource(@RequestParam("id") String id) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    bdpPrmEngineResourceService.defaultResource(id);
    return responseMsg;
  }

  /** 通过平台API将字段值转换为名称，包括通用选择组件、通用代码 */
  private void valueConvert(List<BdpPrmEngineResourceDTO> bdpPrmEngineResourceDTOList) {
    // 循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    if (CollectionUtils.isNotEmpty(bdpPrmEngineResourceDTOList)) {
      for (BdpPrmEngineResourceDTO bdpPrmEngineResource : bdpPrmEngineResourceDTOList) {
        BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, bdpPrmEngineResource.getCreatedBy());
        BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, bdpPrmEngineResource.getSecretLevel());
      }
      if (convertFormData.size() > 0) {
        // 获取请求结果
        Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
        for (BdpPrmEngineResourceDTO bdpPrmEngineResource : bdpPrmEngineResourceDTOList) {
          bdpPrmEngineResource.setCreateUserName(
              BusinessUtil.convertFormat(
                  convertResultData, SystemConstant.USER, bdpPrmEngineResource.getCreatedBy()));
          bdpPrmEngineResource.setSecretLevelName(BusinessUtil.convertFormat(
                  convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, bdpPrmEngineResource.getSecretLevel()));
        }
      }
    }
  }

  @ApiOperation(value = "获取默认存储引擎")
  @ApiImplicitParam(value = "类型", name = "type", dataType = "int")
  @GetMapping("/findDefaultEngineResource")
  public ResponseMsg<BdpPrmEngineResourceDTO> findDefaultEngineResource(int type) {
    ResponseMsg<BdpPrmEngineResourceDTO> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(this.bdpPrmEngineResourceService.findDefaultEngineResource(type));
    return responseMsg;
  }
}
